<template>
  <div class="simple-app-container">
    <div v-loading="loading" v-permission="['base-data:product:info:add']">
      <a-space style="margin-bottom: 16px">
        <a-button type="primary" @click="openDialog('acceptance')">验收</a-button>
        <a-button type="primary" @click="openDialog('warehouse')">入库</a-button>
        <a-button type="primary" @click="openDialog('complete')">完工</a-button>
      </a-space>

      <!-- 将描述列表改为无边框样式 -->
      <a-descriptions :column="4">
        <a-descriptions-item label="生产单号">
          {{ formData.code || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="商品">
          {{ formData.categoryId || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="商品名称">
          {{ formData.shortName || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="计量单位">
          {{ formData.skuCode || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="多属性">
          {{ formData.externalCode || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="订购数量">
          {{ formData.number || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="生产数量">
          {{ formData.number || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="销售订单号">
          {{ formData.spec || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="客户原始单号">
          {{ formData.unit || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="计划完工">
          {{ formData.weight || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="单据备注" :span="2">
          {{ formData.volume || '-' }}
        </a-descriptions-item>
      </a-descriptions>

      <a-col :span="24" style="margin-top: 16px">
        <a-menu v-model:selectedKeys="selectedKeys" mode="horizontal" class="custom-menu" @click="handleTabChange">
          <a-menu-item key="required">1、所需物料</a-menu-item>
          <a-menu-item key="production">2、生产工序</a-menu-item>
        </a-menu>
      </a-col>

      <a-row>
        <a-col :span="24">
          <vxe-grid ref="grid" resizable show-overflow highlight-hover-row keep-source row-id="id" height="390"
            :data="currentTableData" :columns="productColumns" :loading="tableLoading" :toolbar-config="{
              // 缩放
              zoom: false,
              // 自定义表头
              custom: false,
              // 右侧是否显示刷新按钮
              refresh: false,
              // 自定义左侧工具栏
              slots: {
                // buttons: 'toolbar_buttons',
              },
            }">
            <!-- 序号列的自定义渲染 -->
            <template #index_default="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #action_default="{ row }">
              <table-action outside :actions="createActions(row)" />
            </template>
          </vxe-grid>
        </a-col>
      </a-row>

      <div class="form-modal-footer">
        <a-space>
          <a-button type="primary" @click="submit">保存</a-button>
          <a-button @click="closeDialog">关闭</a-button>
        </a-space>
      </div>
    </div>
    <outDialog ref="outdialog" />
  </div>
</template>
<script>
import { defineComponent, h, onMounted, ref } from 'vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { validCode } from '@/utils/validate';
import * as api from '@/api/base-data/product/info';
import * as propertyApi from '@/api/base-data/product/property';
import { Modal } from 'ant-design-vue';
import { tasksProductionApi } from '/@/api/base-data/product/production-tasks';
import * as storeApi from '@/api/base-data/store-center';
import outDialog from './outDialog.vue'
import { useRoute } from 'vue-router';
export default defineComponent({
  name: 'AddProduct',
  components: {
    outDialog,
  },
  setup() {
    const route = useRoute();
    onMounted(() => {
      const id = route.params.id;
      if (!id) {
        console.error('No ID provided');
        return;
      }
      console.log("======================>", id)
    });
    return {
      route,
    }
  },


  data() {
    return {
      PlusOutlined,
      DeleteOutlined,
      h,
      selectedKeys: ['required'], // 默认选中"所需物料"
      itemMenu: "required",
      // 是否显示加载框
      loading: false,
      // 表单数据
      formData: {},
      productType: undefined,
      productBundles: [],
      // 属性列表
      modelorList: [],
      // 表单校验规则
      rules: {
        orderNumber: [
          { message: '请输入生产单号' },
          { validator: validCode, message: '编号必须由字母、数字组成，长度不能超过20位' },
        ],
        name: [{ required: true, message: '请输入名称' }],
        skuCode: [{ message: '请输入SKU编号' }],
        categoryId: [{ required: true, message: '请选择类目' }],
        brandId: [{ required: true, message: '请选择品牌' }],
      },
      itemId: '123',
      outdialog: null,
      materialColumns: [
        // {
        //   field: 'index',
        //   title: '#',
        //   align: 'center',
        //   width: 45,
        //   slots: { default: 'index_default' }
        // },
        { type: 'checkbox', width: 45 },
        {
          field: 'action',
          title: '操作',
          width: 160,
          slots: { default: 'action_default' },
          // fixed: 'left',
        },
        {
          field: 'code',
          title: '编号',
          width: 200,
        },
        {
          field: 'name',
          title: '名称',
          width: 400,
        },
        {
          field: 'unit',
          title: '单位',
          width: 50,
        },
        {
          field: 'number',
          title: '数量',
          width: 50,
        },
        {
          field: 'receive',
          title: '领料数',
          width: 70,
        },
        {
          field: 'return',
          title: '已退数',
          width: 70,
        },
        {
          field: 'use',
          title: '已用数',
          width: 70,
        },
        {
          field: 'note',
          title: '备注',
          width: 100,
        },
      ],
      tableLoading: false,
      currentTableData: [],
      productionColumns: [
        // {
        //   field: 'index',
        //   title: '#',
        //   align: 'center',
        //   width: 45,
        //   slots: { default: 'index_default' }
        // },
        // { type: 'checkbox', width: 45 },
        {
          field: 'code',
          title: '执行工序',
          width: 200,
          // slots: { default: 'fulfillment_default' },
        },
        {
          field: 'name',
          title: '工序名称',
          width: 400,
          // slots: { default: 'name_default' },
        },
        {
          field: 'personnel',
          title: '负责人员',
          width: 200,
          // slots: { default: 'personnel_default' },
        },
        {
          field: 'biling',
          title: '计费方式',
          width: 200,
          // slots: { default: 'biling_default' },
        },
        {
          field: 'retailPri',
          title: '加工单价',
          width: 200,
          // slots: { default: 'retailPrice_default' },
        },
        {
          field: 'completiontime',
          title: '计划完工时间',
          width: 200,
          // slots: { default: 'completiontime_default' },
        },
        {
          field: 'note',
          title: '备注',
          width: 200,
          // slots: { default: 'note_default' },
        },
      ],
    };
  },
  computed: {
    productColumns() {
      return this.itemMenu === 'required' ? this.materialColumns : this.productionColumns;
    }
  },
  created() {
    this.initFormData();
    this.initData();
  },
  methods: {
    async handleTabChange({ key }) {
      this.selectedKeys = [key];
      this.itemMenu = key;
      await this.loadTableData();
    },
    async loadTableData() {
      this.tableLoading = true;
      try {
        let response;
        // if (this.itemMenu === 'required') {
        //   response = await tasksProductionApi.queryMaterialById(this.itemId);
        // } else {
        //   response = await tasksProductionApi.queryProcessById(this.itemId);
        // }
        // 模拟 API 调用延迟
        await new Promise(resolve => setTimeout(resolve, 500));

        if (this.itemMenu === 'required') {
          // 所需物料的模拟数据
          response = {
            datas: [
              {
                id: '1',
                code: 'M001',
                name: '原材料A',
                unit: '个',
                number: 100,
                receive: 50,
                return: 5,
                use: 45,
                note: '常规材料'
              },
              {
                id: '2',
                code: 'M002',
                name: '包装材料B',
                unit: '箱',
                number: 50,
                receive: 30,
                return: 2,
                use: 28,
                note: '易碎品'
              }
            ],
            totalCount: 2
          };
        } else {
          // 生产工序的模拟数据
          response = {
            datas: [
              {
                id: '1',
                code: 'P001',
                name: '组装',
                personnel: '张三',
                biling: '计件',
                retailPri: '5.00',
                completiontime: '2024-01-20',
                note: '需要特殊工具'
              },
              {
                id: '2',
                code: 'P002',
                name: '质检',
                personnel: '李四',
                biling: '计时',
                retailPri: '50.00',
                completiontime: '2024-01-21',
                note: '严格执行质检标准'
              },
              {
                id: '3',
                code: 'P003',
                name: '包装',
                personnel: '王五',
                biling: '计件',
                retailPri: '3.00',
                completiontime: '2024-01-22',
                note: '使用防震包装'
              }
            ],
            totalCount: 3
          };
        }
        this.currentTableData = response.datas;

      } catch (error) {
        console.error('Table Data Load Error:', error);
        this.currentTableData = [];
        this.$message.error('加载数据失败');
      } finally {
        this.tableLoading = false;
      }
    },
    initFormData() {
      const data = [
        { orderNumber: "SC202501160001", categoryId: "1", shortName: "测试商品", skuCode: "123456", brandId: "1", number: 100, brandId: "1", spec: "123456", unit: "123456", weight: "123456", volume: "123456" },
        { orderNumber: "SC202501160002", categoryId: "1", shortName: "测试商品", skuCode: "123456", brandId: "10", number: 10, brandId: "1", spec: "123456", unit: "123456", weight: "123456", volume: "123456" },
        { orderNumber: "SC202501170002", categoryId: "1", shortName: "测试商品", skuCode: "123456", brandId: "10", number: 10, brandId: "1", spec: "123456", unit: "123456", weight: "123456", volume: "123456" }
      ]
      const time = new Date();
      const newOreder = "" + time.getFullYear() + String(time.getMonth() + 1).padStart(2, 0) + String(time.getDate()).padStart(2, 0)
      const maxoldReder = data.filter(item => item.orderNumber.split("").filter(item => !isNaN(item)).join("").slice(0, 8) === newOreder).sort((a, b) => b.orderNumber.split("").filter(item => !isNaN(item)).join("").slice(8, 12) - a.orderNumber.split("").filter(item => !isNaN(item)).join("").slice(9, 12))[0]
      const number = data.map(item => item.orderNumber.split("").filter(item => !isNaN(item)).join(""))
      if (maxoldReder) {
        const num = Number(maxoldReder.orderNumber.split("").filter(item => !isNaN(item)).join("").slice(8, 12)) + 1
        const newOrder = newOreder + String(num).padStart(4, 0)
        this.formData.orderNumber = "SC" + newOrder
      } else {
        this.formData.orderNumber = "SC" + newOreder + "0001"
      }
      this.modelorList = [];
      this.productBundles = [];
    },
    async submit() {
      const that = this;
      let valid = true;

      await this.$refs.form.validate().then((res) => {
        valid = res;
      });

      this.loading = true;
      api
        .create(params)
        .then((res) => {
          this.$msg.createSuccess('新增成功！');
          this.$emit('confirm');
          this.closeDialog();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    selectCategory(val) {
      this.modelorList = [];
      if (!this.$utils.isEmpty(val)) {
        propertyApi.getModelorByCategory(val).then((res) => {
          this.modelorList = res;
        });
      }
    },
    addRow() {
      this.currentTableData.push(this.emptyProduct());
    },
    emptyProduct() {
      return {
        id: this.$utils.uuid(),
        productId: '',
        bundleNum: 1,
        biling: "计时"
      };
    },
    delRow() {
      const records = this.$refs.grid.getCheckboxRecords();
      if (this.$utils.isEmpty(records)) {
        this.$msg.createError('请选择要删除的商品数据！');
        return;
      }

      this.$msg.createConfirm('是否确定删除选中的商品？').then(() => {
        this.productBundles = this.productBundles.filter((t) => {
          const tmp = records.filter((item) => item.id === t.id);
          return this.$utils.isEmpty(tmp);
        });
      });
    },
    openDialog(type) {
      switch (type) {
        case 'acceptance':
          this.$refs.outdialog.showModal(0, { id: this.route.params.id });
          this.acceptanceVisible = true;
          break;
        case 'warehouse':
          this.$refs.outdialog.showModal(1, { id: this.route.params.id });
          this.warehouseVisible = true;
          break;
        case 'complete':
          this.handleComplete();
          break;
      }
    },
    handleComplete() {
      Modal.confirm({
        title: '确认完工',
        content: '是否确认将该生产任务标记为完工？完工后将无法修改。',
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          try {
            this.loading = true;

            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500));
            const response = await tasksProductionApi.completed(this.itemId);

            this.$message.success('完工操作成功');
            this.$router.go(-1);
          } catch (error) {
            console.error('Complete Error:', error);
            this.$message.error('完工操作失败');
          } finally {
            this.loading = false;
          }
        },
      });
    },
    createActions(row) {
      const actions = [];
      actions.push({
        label: '领料',
        onClick: () => {
          row = Object.assign({ ...row, material: this.route.params.id });
          this.$refs.outdialog.showModal(2, row);
        }
      });

      actions.push({
        label: '退料',
        onClick: () => {
          row = Object.assign({ ...row, material: this.route.params.id });
          this.$refs.outdialog.showModal(3, row);
        }
      });
      actions.push({
        label: '用料',
        onClick: () => {
          row = Object.assign({ ...row, material: this.route.params.id });
          this.$refs.outdialog.showModal(4, row);
        }
      });
      return actions;
    },
    handleAcceptanceOk() {
      this.acceptanceVisible = false;
    },
    handleWarehouseOk() {
      this.warehouseVisible = false;
    },
    closeDialog() {
      this.$utils.closeCurrentPage();
      this.$router.go(-1);
    },
    async initData() {
      await this.loadTableData();
    }
  },
});
</script>
<style lang="less" scoped>
.summary-row {
  margin-top: 16px;
  padding: 12px;
  background-color: #fafafa;
  border-radius: 4px;
  height: 48px;
  display: flex;
  align-items: center;

  .summary-label {
    font-weight: bold;
    margin-right: 8px;
  }

  .summary-value {
    color: #1890ff;
    font-size: 16px;

    .vacant {
      display: block;
      height: 24px;
      visibility: hidden;
    }
  }
}

/deep/ .ant-menu-item {
  min-width: 120px;
  padding: 0 24px;
  text-align: center;
}

// 更新描述列表的样式
:deep(.ant-descriptions) {
  margin-bottom: 16px;

  .ant-descriptions-item {
    padding-bottom: 12px;
  }

  .ant-descriptions-item-label {
    color: rgba(0, 0, 0, 0.85);
    font-weight: normal;
    padding-right: 8px;
  }

  .ant-descriptions-item-content {
    color: rgba(0, 0, 0, 0.65);
  }
}
</style>
